<script setup lang="ts">
import { ref } from "vue"
import { ElMessage } from 'element-plus';
import { getCertificationIdApi } from "#/api/certificate/template"
import AsyncImage from './async-image.vue';
import { obsUpload } from "#/utils/obs"

import html2pdf from 'html2pdf.js';

defineOptions({ name: 'Dialog' })

const dialogVisible = ref(false)
const certifiRef = ref()
const certifiInfo = ref()
const loading = ref(false)
const loadingBtn = ref(false)
const showCertifi = ref(false)
const templateFile = ref()

const handleClose = () => {
  showCertifi.value = false
  dialogVisible.value = false
}

// 查询证书模板
const getTemplateData = (id: any) => {
  loading.value = true
  getCertificationIdApi(id).then(res => {
    if (res) {
      templateFile.value = res.templateFile
    }
  }).finally(() => {
    loading.value = false
  })
}

const inint = (data: any) => {
  certifiInfo.value = data
  if (data?.certifiedId) {
    getTemplateData(data?.certifiedId)
  }
  dialogVisible.value = true
}

const imageLoaded = () => {
  showCertifi.value = true
  handleHtmlTopdf('UPLOAD')
}

const resObsUpload = (file: any, fileName: any) => {
  return new Promise((resolve, reject) => {
    obsUpload({
      Key: `certificate/${fileName}`,
      SourceFile: file,
    }, (err: any, result: any) => {
      if (err) {
        reject(err)
        return
      }
      resolve(result)
    })
  })
}

async function handleHtmlTopdf(handleType:string) {
  try {

    // 获取要导出的元素
    let element = document.querySelector('#certifiRef') as HTMLElement;

    if (!element) return

    // 配置选项
    const customFileName = `${certifiInfo.value.certificateNumber}.pdf`
    const opt = {
      margin: [5, 10, 5, 10],
      fileName: customFileName,
      enableLinks: false,
      image: { type: 'jpeg', quality: 1 },
      html2canvas: {
        scale: 2, // 提高清晰度
        logging: false,
        useCORS: true, // 允许跨域图片
      },
      jsPDF: {
        unit: 'mm',
        format: 'a4',
        orientation: 'portrait',
      },
      pagebreak: {mode: ['css', 'legacy'], avoid: ['.exam-type-title', '.q-title', '.image-war', '.q-option-content', 'img'] },
    };
    // 显示加载状态
    loadingBtn.value = true;

    // 生成并上传PDF
    if (handleType === 'UPLOAD') {
      const pdfBlob = await html2pdf().from(element).set(opt).toPdf().get('pdf').then((pdf:any) => {
        return new Blob(
          [pdf.output('blob')], 
          { type: 'application/pdf' }
        );
      });
      const uploadRes:any = await resObsUpload(pdfBlob, customFileName)
      if (uploadRes?.CommonMsg) {
      }
    }

    // 生成并下载PDF
    if (handleType === 'DOWNLOAD') {
      await html2pdf().from(element).set(opt).save();
    }

    // 生成并打印PDF
    if (handleType === 'PRINT') {
      await html2pdf()
      .from(element)
      .set(opt)
      .toPdf()
      .get('pdf')
      .then((pdf:any) => {
        const pdfBlob = pdf.output('blob');
        const pdfUrl = URL.createObjectURL(pdfBlob);
        // 打开新窗口并触发打印
        const printWindow = window.open(pdfUrl);
        printWindow?.addEventListener('load', () => {
          printWindow.print();
        });
      });
    }
  } catch (error) {
    console.log(error)
  } finally {
    loadingBtn.value = false;
  }
}

defineExpose({ inint })

</script>
<template>
  <el-dialog v-model="dialogVisible" align-center center :destroy-on-close="true" :title="$t('whiteLink.previewCertifiTxt')" width="650px" :append-to-body="true"
    :close-on-click-modal="false" :before-close="handleClose">
    <div v-loading="loading" class="pl-[15px] pr-[15px] pt-[10px] pb-[10px] ">
      <div ref="certifiRef" id="certifiRef" v-show="showCertifi" class="min-h-[500px] certifi-war">
        <div class="name text-3xl">{{certifiInfo.nameCn}}</div>
        <div class="name-cn text-2xl">{{certifiInfo.nameEn}}</div>
        <div class="certifi-code text-2xl">{{certifiInfo.certificateNumber}}</div>
        <div class="push-time text-lg">{{certifiInfo.meansTime}}</div>
        <div class="effective-time text-lg">{{certifiInfo.validTime}}</div>
        <AsyncImage v-if="templateFile" :src="templateFile" @image-loaded="imageLoaded" />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer text-center">
      </div>
    </template>
  </el-dialog>
</template>
<style lang="less" scoped>
  .certifi-war {
    position: relative;
    .name {
      display: inline-block;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%);
      z-index: 1;
    }
    .name-cn {
      display: inline-block;
      position: absolute;
      top: 55%;
      left: 50%;
      z-index: 1;
      transform: translateX(-50%);
    }
    .certifi-code {
      display: inline-block;
      position: absolute;
      top: 64.75%;
      left: 43%;
      z-index: 1;
    }
    .push-time {
      display: inline-block;
      position: absolute;
      top: 78.0%;
      left: 24.5%;
      z-index: 1;
    }
    .effective-time {
      display: inline-block;
      position: absolute;
      top: 81.0%;
      left: 24.5%;
      z-index: 1;
    }
  }
</style>
